<?php

use Yaf\Registry;
use Yaf\Controller_Abstract;

/**
 * 控制器基类
 * Class BaseController
 */
class BaseController extends Controller_Abstract
{
    /**
     * 自定义请求对象
     * @var Request
     */
    protected $MyRequest = null;

    /**
     * 自定义响应对象
     * @var Response
     */
    protected $MyResponse = null;

    /**
     * 创建成员，初始化注册表
     * 功能：兼容接收JSON和XML的参数，格式化Header
     * 步骤：创建自定义的请求对象、响应对象，再把对象放入注册表
     */
    protected function createMemberRegistry()
    {
        // 创建自定义对象
        $this->MyRequest = new Request();
        $this->MyResponse = new Response($this->getResponse());
        // 把对象放入注册表
        Registry::set(Constant::Registry_MY_REQUEST, $this->MyRequest);
        Registry::set(Constant::Registry_MY_RESPONSE, $this->MyResponse);
    }

    /**
     * JSON响应
     *
     * @param array $data
     * @param int $ret
     * @param string $msg
     * @return bool
     */
    protected function json(array $data = [], int $ret = 200, string $msg = ''):bool
    {
        // 延迟创建
        if ($this->MyResponse === null) {
            $this->createMemberRegistry();
        }
        $this->MyResponse->setAll($data, $ret, $msg)->output();
        return false;
    }

    /**
     * 添加允许跨域的报文头
     */
    protected function Cors()
    {
        $header = [
            'access-control-allow-origin' => '*',
            'access-control-allow-credentials' => 'true',
            'access-control-allow-headers' => 'Content-Type,X-Requested-With',
            'access-control-allow-methods' => 'GET,POST'
        ];
        $response = $this->getResponse();
        Response::handleHeaders($response, $header);
        // 响应OPTIONS请求
        if ($this->getRequest()->isOptions()) {
            $response->response();
            exit(0);
        }
    }
}
